#include "stm32f10x.h"
#include <rtthread.h>
#include "touch.h"

#include <../rtgui/event.h>
#include <../rtgui/kbddef.h>
#include <../rtgui/rtgui_server.h>
#include <../rtgui/rtgui_system.h>







struct rtgui_touch_device
{
    struct rt_device parent;

    rt_timer_t poll_timer;
    rt_uint16_t x, y;

    rt_bool_t calibrating;
    rt_touch_calibration_func_t calibration_func;

    rt_uint16_t min_x, max_x;
    rt_uint16_t min_y, max_y;
};
static struct rtgui_touch_device *touch = RT_NULL;



















/* RT-Thread Device Interface */
static rt_err_t rtgui_touch_init (rt_device_t dev)
{

 
    return RT_EOK;
}

static rt_err_t rtgui_touch_control (rt_device_t dev, rt_uint8_t cmd, void *args)
{
    switch (cmd)
    {
    case RT_TOUCH_CALIBRATION:
        touch->calibrating = RT_TRUE;
        touch->calibration_func = (rt_touch_calibration_func_t)args;
        break;

    case RT_TOUCH_NORMAL:
        touch->calibrating = RT_FALSE;
        break;

    case RT_TOUCH_CALIBRATION_DATA:
    {
        struct calibration_data* data;

        data = (struct calibration_data*) args;

        //update
        touch->min_x = data->min_x;
        touch->max_x = data->max_x;
        touch->min_y = data->min_y;
        touch->max_y = data->max_y;

        //save setup
        
    }
    break;
    }

    return RT_EOK;
}

void touch_timeout(void* parameter)
{
    struct rtgui_event_mouse emouse;

 
    /* send event to server */
   	if (touch->calibrating != RT_TRUE)
        rtgui_server_post_event(&emouse.parent, sizeof(struct rtgui_event_mouse));
		else rt_kprintf("error when send event to server.\n") ;
}



void rtgui_touch_hw_init(void)
{

    touch = (struct rtgui_touch_device*)rt_malloc (sizeof(struct rtgui_touch_device));
    if (touch == RT_NULL) return; /* no memory yet */

    /* clear device structure */
    rt_memset(&(touch->parent), 0, sizeof(struct rt_device));
    touch->calibrating = RT_FALSE;
    touch->min_x = 350;
    touch->max_x = 3500;
    touch->min_y = 350;
    touch->max_y = 3800;

    /* init device structure */
    touch->parent.type = RT_Device_Class_Unknown;
    touch->parent.init = rtgui_touch_init;
    touch->parent.control = rtgui_touch_control;
 
    /* create 1/8 second timer */
    touch->poll_timer = rt_timer_create("touch", touch_timeout, RT_NULL,
                                        RT_TICK_PER_SECOND/100, RT_TIMER_FLAG_PERIODIC);

    /* register touch device to RT-Thread */
    rt_device_register(&(touch->parent), "touch", RT_DEVICE_FLAG_RDWR);
	rt_device_open(&(touch->parent), RT_DEVICE_FLAG_RDWR);
	if (touch->poll_timer != RT_NULL)	rt_timer_start(touch->poll_timer);
	else  rt_kprintf("touch create error.\n");

}

